package com.elink.enginerring.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.elink.enginerring.co.BaseCo;
import com.elink.enginerring.common.ErrorType;
import com.elink.enginerring.common.Pagination;
import com.elink.enginerring.dao.CollectionMapper;
import com.elink.enginerring.dao.PostbarMapper;
import com.elink.enginerring.domain.Collection;
import com.elink.enginerring.domain.Postbar;
import com.elink.enginerring.service.CollectionService;
import com.elink.enginerring.util.JSONUtil;

@Service
public class CollectionServiceImpl implements CollectionService {
	@Autowired
	private CollectionMapper collectionMapper;
	@Autowired
	private PostbarMapper postbarMapper;
	
	@Override
	public Map<String, Object> updateCollect(String userId, String postbarId) {
		Postbar postbar = 	postbarMapper.selectByPrimaryKey(postbarId);
		if(postbar != null ){
			int count = collectionMapper.select(userId,postbarId);
			if(count == 0 ){ //表示没有收藏过
				Collection c = new Collection();
				c.setUserId(userId);
				c.setPostbarId(postbarId);
				c.setCollectionTime(new Date());
				collectionMapper.insertSelective(c);
				//问题的收藏数加一
				postbar.setCollectionCount(postbar.getCollectionCount()+1);
				postbarMapper.updateByPrimaryKeySelective(postbar);
				
				return JSONUtil.getJSON(ErrorType.COLLECTION_SUCCESS);
			}else{
				collectionMapper.delete(userId,postbarId);
				//问题的收藏数减1
				postbar.setCollectionCount(postbar.getCollectionCount()-1);
				postbarMapper.updateByPrimaryKeySelective(postbar);
				
				return JSONUtil.getJSON(ErrorType.CANCEL_COLLECTION);
			}
			
		}else{
			return JSONUtil.getJSON(ErrorType.FILE_COMMENT_ERROR);
		}
	}

	@Override
	public Map<String, Object> getMyCollect(BaseCo co,String userId) {
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		map.put("list", postbarMapper.getMyCollect(co,userId));
		map.put("Pagination",   new Pagination(co, postbarMapper.selectCountMyCollect(userId)) );
		
		return JSONUtil.getJSON(ErrorType.SUCCESS,map);
	}

}
